import { access } from '@/api';
import { DataType } from '@/pages/AccessKey/constant';
import { useModel } from '@umijs/max';
import { useEffect, useState } from 'react';

export default function useAccessList() {
  const [loading, setLoading] = useState(false);
  const { userId } = useModel('global');
  const [data, setData] = useState<DataType[]>([]);
  const [fresh, setFresh] = useState(true);

  useEffect(() => {
    if (!fresh) return;
    setLoading(true);
    access.getAccessList(userId).then((res) => {
      let newData = res.data?.sort((a: DataType, b: DataType) => {
        if (a.disable === b.disable) return 0;
        return a.disable ? 1 : -1;
      });
      setData(newData || []);
      setLoading(false);
      setFresh(false);
    });
  }, [userId, fresh]);

  return { data, loading, setFresh };
}
